package com.shenmazong.demosecurity0719.security;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;

/**
 * @author 军哥
 * @version 1.0
 * @description: 自定义用户验证的bean
 * @date 2021/7/19 16:00
 */

@Component
@Slf4j
public class MyAuthenticationProvider implements AuthenticationProvider {

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        log.info("authenticate:来登录了");
        //--1 表单输入的用户名和密码
        String username = (String) authentication.getPrincipal();
        String password = (String) authentication.getCredentials();
        log.info("username={},password={}", username, password);

        //--2 判断用户名和密码
        if(!username.equals("david") && !username.equals("admin")) {
            throw new BadCredentialsException("用户不存在!");
        }
        if(!password.equals("123")) {
            throw new BadCredentialsException("密码不正确!");
        }

        //--3 临时的：真实环境需要从数据库中获取用户的信息和权限
        MyUserDetail user = new MyUserDetail();
        user.setName(username);
        user.setPass(password);

        MyRole myRole = new MyRole();
        if(username.equals("david")) {
            myRole.setRoleName("select");
        }
        else if(username.equals("admin")) {
            myRole.setRoleName("delete");
        }

        ArrayList<MyRole> myRoles = new ArrayList<>();
        myRoles.add(myRole);

        user.setRoles(myRoles);

        //--4 把用户的信息存储到SpringSecurity上下文中
        return new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
